package com.zhou.common.mybatis.template.shiro.swagger;

import com.fasterxml.classmate.ResolvedType;
import io.swagger.annotations.ApiModelProperty;
import lombok.extern.slf4j.Slf4j;
import springfox.documentation.schema.Annotations;
import springfox.documentation.service.AllowableListValues;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.schema.ModelPropertyBuilderPlugin;
import springfox.documentation.spi.schema.contexts.ModelPropertyContext;
import springfox.documentation.swagger.schema.ApiModelProperties;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Slf4j
public class EnumPropertyDisplayConfig implements ModelPropertyBuilderPlugin {

    @Override
    public void apply(ModelPropertyContext context) {

        Optional<ApiModelProperty> annotation = java.util.Optional.empty();
        if (context.getAnnotatedElement().isPresent()) {
            annotation = java.util.Optional.ofNullable(annotation.orElseGet(
                    ApiModelProperties.findApiModePropertyAnnotation(context.getAnnotatedElement().get())::get));
        }
        if (!annotation.isPresent() && context.getBeanPropertyDefinition().isPresent()) {
            annotation = Annotations.findPropertyAnnotation(
                    context.getBeanPropertyDefinition().get(),
                    ApiModelProperty.class);
        }

        final Class<?> rawPrimaryType = context.getBeanPropertyDefinition().get().getRawPrimaryType();
        //过滤得到目标类型
        if (annotation.isPresent() && EnumDescription.class.isAssignableFrom(rawPrimaryType)) {
            log.info("des={}", annotation.get().value());
            //获取CodedEnum的code值
            EnumDescription[] values = (EnumDescription[]) rawPrimaryType.getEnumConstants();
            final List<String> displayValues = Arrays.stream(values).map(codedEnum -> codedEnum.getCode() + codedEnum.getInfo()).collect(Collectors.toList());
            final AllowableListValues allowableListValues = new AllowableListValues(displayValues, rawPrimaryType.getTypeName());
            //固定设置为int类型
            final ResolvedType resolvedType = context.getResolver().resolve(int.class);
            context.getBuilder().description(annotation.get().value() + ":" + displayValues).type(resolvedType).allowableValues(allowableListValues);
//            context.getBuilder().allowableValues(allowableListValues).type(resolvedType);
        }
    }

    @Override
    public boolean supports(DocumentationType documentationType) {
        return true;
    }
}
